package org.weasel.business;

import java.io.File;

import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;

import org.w3c.dom.Document;

public class XMLValidator {
	public static final String WEASEL_XSD = "./weasel.xsd";
	private static XMLValidator instance = null;
	
	public static XMLValidator getInstance() {
		if(instance == null)
			instance = new XMLValidator();
		return instance;
	}
	
	/**
	 * This method validates a given xml file againsta xml schema specified in the WEASEL_XSD constant.
	 * It returns true if the xml file is valid and false if any error occurs which may be file not found or any other error.
	 * @param path
	 * @return
	 */
	public boolean isValidXMLFile(String path) {
        try {
            // Parse an XML document into a DOM tree.
            DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            Document document = parser.parse(new File(path));

            // Create a SchemaFactory capable of understanding WXS schemas.
            SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

            // Load a WXS schema, represented by a Schema instance.
            Source schemaFile = new StreamSource(new File(WEASEL_XSD));
            Schema schema = factory.newSchema(schemaFile);

            // Create a Validator object, which can be used to validate
            // an instance document.
            Validator validator = schema.newValidator();

            // Validate the DOM tree.
            validator.validate(new DOMSource(document));

        } catch (Exception e) {
        	System.out.println(e.getMessage());
        	//if an error occur the document is not valid
        	return false;
        }
        return true;
	}
}
